package org.eden.heartbeat.core;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eden.heartbeat.api.configuration.ApplicationConfiguration;
import org.eden.heartbeat.api.exception.JMXException;
import org.eden.heartbeat.api.jmx.HeartbeatCoreMBean;
import org.eden.heartbeat.api.jmx.HeartbeatJMXService;

/**
* Class that gracefully shuts down the Heartbeat Core.
*
* @author trsimoes
* @version $Revision:$
*/
public class HeartbeatCoreShutdown {

    private static Log LOG = LogFactory.getLog(HeartbeatCoreShutdown.class);

    private HeartbeatJMXService heartbeatJMXService = HeartbeatJMXService.getInstance();

    public void execute() {
        try {
            if (LOG.isInfoEnabled()) {
                LOG.info("Heartbeat core shutdown started");
            }

            // load configurations
            ApplicationConfiguration.loadConfigurations();

            // start the jmx service
            this.heartbeatJMXService.start();

            HeartbeatCoreMBean coreProxy = this.heartbeatJMXService.getHeartbeatCoreProxy();
            coreProxy.stop();
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Error running shutdown command", e);
            }
        } finally {
            try {
                // clean up and exit
                this.heartbeatJMXService.close();

                if (LOG.isInfoEnabled()) {
                    LOG.info("Heartbeat core shutdown terminated successfully.");
                }

            } catch (JMXException e) {
                if (LOG.isErrorEnabled()) {
                    LOG.error("Error closing the JMX service before shutting down the console.", e);
                }
            }
        }
    }

    public static void main(String[] args) {
        HeartbeatCoreShutdown console = new HeartbeatCoreShutdown();
        console.execute();
    }
}